/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package main;

import java.io.IOException;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

/**
 *
 * @author Administrator
 */
public class ChooseTableScene extends Scene {
    
    private static final int NUMBER_TABLE_PER_PAGE = 9;
    private static final int NUMBER_TABLE_PER_ROW = 3;
    private static final int NUMBER_TABLE_PER_COLUMN = 3;
    private static final int NUMER_PAGES = 9;
    private static final int DISTANCE_BETWEEN_DOT = 5;
    protected static final int NUMBER_TABLES = 40;
    private boolean isDrawSelected;
    private boolean isPointerDrag;
    private boolean isShowPassBox;
    //------------------------------------------------------------------------
    private int numberTablesShow;
    private int dotPaddingLeft;
    private int dotImageWidth;
    private int tableHeight;
    private int tableWidth;
    private int paddingTop;
    private int paddingLeft;
    private int startDrawIndex;
    private int tableSelectedIndex;
    private int currentPageIndex;
//    private int myMoney;
    private int pointerPressX;
    private int poiterPressY;
    private int pointerDragX;
    private int pointerDragY;
    private int gamePlayType;
    //-----------------------------------------------------------------------
//    private int[] moneyBetOfTables;
    private int[] numberPlayerInTable;
    //-----------------------------------------------------------------------
    private Image topBarImage;
    private Image bottomBarImage;
    private Image tableImage;
    private Image dotImages;
    private Image avatarImage;
    private String gameName;
    private String[] menuString = {"Thông tin cá nhân", "Chơi nhanh", "Hộp thư", "Loa"};
    private CustomTextBox passBox;
    private Dialog dialog;
    
    public ChooseTableScene(MainCanvas parent) {
        super(parent);
        initValue();
        initObject();
    }
    
    private void initValue() {
        Debug.d("my money :" + gameData.getMyMoney());
        numberTablesShow = NUMBER_TABLE_PER_PAGE;
        isDrawSelected = true;
        if (gameData.getKickOut()) {
            dialogString = "Bạn bị kick bởi chủ bàn";
            gameData.setKickOut(false);
        } else if (gameData.isOutOfMoney) {
            dialogString = "Bạn đã không đủ tiền chơi tiếp";
            gameData.isOutOfMoney = false;
        } else {
            dialogString = "";
        }
        gamePlayType = gameData.getGameTypePlay();
        gameName = getGameName();
        numberPlayerInTable = gameData.getNumberPlayerInTable();
//        moneyBetOfTables = gameData.getMoneyBetOfTable();
        Request.updateMoney();
//        myMoney = gameData.getMyMoney();

        parent.repaint();
    }
    
    private String getGameName() {
        switch (gamePlayType) {
            case Constants.CO_VUA:
                return "Cờ vua";
            case Constants.CUA_HANG:
            case Constants.PHOM:
                return "Phỏm";
            case Constants.BA_CAY:
                return "Ba cay";
            case Constants.TIEN_LEN:
                return "Tiến lên";
            case Constants.XENG:
                return "Xèng";
            
        }
        return "";
    }
    
    private void initObject() {
        try {
            initImage();
            passBox = new CustomTextBox(PiPoDesigner.COLOR_BLACK, PiPoDesigner.COLOR_WHITE, false, keyPad);
            subMenu.setList(menuString);
            dialog = new Dialog(1, keyPad);
            // initArray();
        } catch (IOException ex) {
        }
    }
    
    private void initImage() throws IOException {
        Image topBarPiece = Utils.loadImage("top_bar_piece.png");
        topBarImage = Utils.creatImageFromPiece(topBarPiece, 1, canvasWidth);
        Image bottomBarPiece = Utils.loadImage("bottom_bar_piece.png");
        bottomBarImage = Utils.creatImageFromPiece(bottomBarPiece, 1, canvasWidth);
        tableImage = Utils.loadImage("table.png");
        tableHeight = tableImage.getHeight();
        tableWidth = tableImage.getWidth();
        paddingTop = (canvasHeight - bottomBarImage.getHeight() - topBarImage.getHeight()
                - NUMBER_TABLE_PER_COLUMN * tableHeight) / (NUMBER_TABLE_PER_COLUMN + 1);
        paddingLeft = (canvasWidth - tableWidth * NUMBER_TABLE_PER_ROW) / (NUMBER_TABLE_PER_ROW + 1);
        dotImages = Utils.loadImage("dot.png");
        dotPaddingLeft = (canvasWidth - NUMER_PAGES * (dotImages.getWidth() / 2 + DISTANCE_BETWEEN_DOT) - DISTANCE_BETWEEN_DOT) / 2;
        dotImageWidth = dotImages.getWidth() / 2;
        avatarImage = Utils.loadImage("avatar_table.png");
    }
    //--------------------------------------------------------------------

    public void setListSubMenu() {
    }
    
    public void doLoop() {
        if (dialog.isShow) {
            dialog.run();
            parent.repaint();
        }
        if (isShowSpeaker) {
            speakerBox.run();
            parent.repaint();
        }
        if (speakFlyString != null) {
            if (speakFlyString.isShow) {
                speakFlyString.run();
                parent.repaint();
            }
        }
    }
//-------------------------------------------------------------------------

    public void paintComponents(Graphics g) {
        paintTable(g);
        paintBarMenu(g);
        if (isShowPassBox) {
            passBox.paint(g, leftScreen + 5, canvasHeight - bottomBarHeight - 20, canvasWidth - 10, 20);
        }
        dialog.paintInput(g, leftScreen + 10, canvasHeight - 5, canvasWidth - 20);
        
    }
    
    private void paintTable(Graphics g) {
        int topList = topScreen + 10 + topBarImage.getHeight();
        int leftList = leftScreen + paddingLeft;
        for (int i = startDrawIndex % NUMBER_TABLE_PER_PAGE; i < numberTablesShow; i++) {
            if (i % NUMBER_TABLE_PER_ROW == 0 && i != 0) {
                leftList = leftScreen + paddingLeft;
                topList += tableHeight + paddingTop;
            }
            if (i == tableSelectedIndex && isDrawSelected) {
                g.drawRoundRect(leftList - 5, topList - 5, tableWidth + 10, tableHeight + 10, 2, 2);
            }
            g.drawImage(tableImage, leftList, topList, 0);
            //paint number player
            paintNumberPlayer(g, leftList, topList, i + startDrawIndex);
            //
            PiPoDesigner.drawCenterString(g, String.valueOf(i + 1 + startDrawIndex), PiPoDesigner.COLOR_BLACK,
                    PiPoDesigner.COLOR_WHITE, leftList + 30, topList + 25);
            String moneyBet = String.valueOf(gameData.getMoneyBetOfTable()[i + startDrawIndex]);
            PiPoDesigner.drawCenterString(g, moneyBet, PiPoDesigner.COLOR_BLACK,
                    PiPoDesigner.COLOR_YELOW, leftList + 25, topList + 10);
            leftList += tableImage.getWidth() + paddingLeft;
        }
    }
    
    private void paintNumberPlayer(Graphics g, int leftList, int topList, int index) {
        // Debug.d("index :" + index+","+numberPlayerInTable[index]);
        try {
            int leftInTable = leftList - 2;
            int topInTable = topList - 2;
            
            int numberPlayersInTable = (numberPlayerInTable[index] < gameData.getMaxPlayer() ? numberPlayerInTable[index] : gameData.getMaxPlayer());
            for (int j = 0, l = numberPlayersInTable; j < l; j++) {
                if (j % 2 == 0 && j != 0) {
                    leftInTable = leftList;
                    topInTable += 32;
                }
                g.drawImage(avatarImage, leftInTable, topInTable, 0);
                leftInTable += 32;
            }
        } catch (Exception ex) {
            Debug.d("num :" + index);
        }
    }
    
    protected void paintBarMenu(Graphics g) {
        
        g.drawImage(topBarImage, leftScreen, topScreen, 0);
        g.drawImage(bottomBarImage, leftScreen, canvasHeight - bottomBarImage.getHeight(), 0);
        paintGameName(g);
        if (isShowSpeaker) {
            paintBarTextBox(g);
            return;
        }
        if (screenMode == SCREEN_PORTRAIT) {
            PiPoDesigner.drawString(g, "Vào", PiPoDesigner.COLOR_BLACK, PiPoDesigner.COLOR_WHITE, canvasWidth / 2 - 15, canvasHeight - 25);
        } else {
            paintPageMark(g);
        }
        PiPoDesigner.drawString(g, "Menu", PiPoDesigner.COLOR_BLACK, PiPoDesigner.COLOR_WHITE, leftScreen + 5, canvasHeight - 25);
        if (isShowSubMenu) {
            PiPoDesigner.drawString(g, "Đóng", PiPoDesigner.COLOR_BLACK, PiPoDesigner.COLOR_WHITE, canvasWidth - 40, canvasHeight - 25);
        } else {
            PiPoDesigner.drawString(g, "Thoát", PiPoDesigner.COLOR_BLACK, PiPoDesigner.COLOR_WHITE, canvasWidth - 40, canvasHeight - 25);
        }
    }
    
    private void paintGameName(Graphics g) {
        PiPoDesigner.drawString(g, gameName, PiPoDesigner.COLOR_BLACK, PiPoDesigner.COLOR_YELOW, canvasWidth / 2 - PiPoDesigner.stringWidth(gameName) / 2,
                5);
    }
    
    private void paintPageMark(Graphics g) {
        for (int i = 0; i < NUMER_PAGES; i++) {
            if (i == currentPageIndex) {
                Utils.drawFrame(g, dotImages, dotPaddingLeft + (DISTANCE_BETWEEN_DOT + dotImageWidth) * i,
                        canvasHeight - bottomBarImage.getHeight() + 5,
                        0, 0, dotImages.getWidth() / 2, dotImages.getHeight());
            } else {
                Utils.drawFrame(g, dotImages, dotPaddingLeft + (DISTANCE_BETWEEN_DOT + dotImageWidth) * i,
                        canvasHeight - bottomBarImage.getHeight() + 5, 1, 0, dotImages.getWidth() / 2, dotImages.getHeight());
            }
        }
    }

    //------------------------------------------------------------------
    public void doKeyLeft() {
        if (isShowUserInfo) {
            moveLeftInfo();
            return;
        }
        tableSelectedIndex--;
        if (tableSelectedIndex % NUMBER_TABLE_PER_ROW == NUMBER_TABLE_PER_ROW - 1 || tableSelectedIndex < 0) {
            startDrawIndex -= NUMBER_TABLE_PER_PAGE;
            tableSelectedIndex = 0;
            currentPageIndex = startDrawIndex / NUMBER_TABLE_PER_PAGE;
            numberTablesShow = NUMBER_TABLE_PER_PAGE;
            //  Debug.d("start :" + startDrawIndex);
        }
        if (startDrawIndex < 0) {
            startDrawIndex = NUMBER_TABLES - (NUMBER_TABLES % NUMBER_TABLE_PER_PAGE);
            numberTablesShow = (NUMBER_TABLES - startDrawIndex);
            currentPageIndex = startDrawIndex / NUMBER_TABLE_PER_PAGE;
        }
//        Debug.d("start draw index :" + startDrawIndex);
//        Debug.d("number talbe :" + numberTablesShow);
//        Debug.d("current page :" + currentPageIndex);

        parent.repaint();
    }
    
    public void doKeyRight() {
        if (isShowUserInfo) {
            moveRightInfo();
            return;
        }
        tableSelectedIndex++;
        if (tableSelectedIndex % NUMBER_TABLE_PER_ROW == 0) {
            startDrawIndex += NUMBER_TABLE_PER_PAGE;
            tableSelectedIndex = 0;
            currentPageIndex = startDrawIndex / NUMBER_TABLE_PER_PAGE;
//            if (currentPageIndex > NUMBER_TABLES / NUMBER_TABLE_PER_PAGE) {
//                currentPageIndex = 0;
//            }
        }
        if (startDrawIndex + NUMBER_TABLE_PER_PAGE > NUMBER_TABLES - 1) {
            numberTablesShow = (NUMBER_TABLES - startDrawIndex);
        }
        Debug.d("current page :" + currentPageIndex);
        Debug.d("max page :" + (NUMBER_TABLES / NUMBER_TABLE_PER_PAGE));
        
        if (currentPageIndex > NUMBER_TABLES / NUMBER_TABLE_PER_PAGE || currentPageIndex == NUMBER_TABLES / NUMBER_TABLE_PER_PAGE && tableSelectedIndex == numberTablesShow) {
            startDrawIndex = 0;
            numberTablesShow = NUMBER_TABLE_PER_PAGE;
            tableSelectedIndex = 0;
            currentPageIndex = 0;
            Debug.d("chuyen trang dau");
        }
        parent.repaint();
    }
    
    protected void doKeyUpRemain() {
        tableSelectedIndex -= NUMBER_TABLE_PER_ROW;
        if (tableSelectedIndex < 0) {
            tableSelectedIndex += NUMBER_TABLE_PER_PAGE;
            if (currentPageIndex == 4) {
                tableSelectedIndex = 3;
            }
        }
        
        parent.repaint();
    }
    
    protected void doKeyDownRemain() {
        tableSelectedIndex += NUMBER_TABLE_PER_ROW;
        if (tableSelectedIndex >= numberTablesShow) {
            tableSelectedIndex = tableSelectedIndex % NUMBER_TABLE_PER_ROW;
        }
        parent.repaint();
    }
    
    protected void doSoftKeyLeftRemain() {
    }
    
    protected void doSoftKeyRightRemain() {
        if (dialog.isShow) {
            dialog.doSoftKeyRight();
            parent.repaint();
            return;
        }
        Request.exitChoooseTable();
        isLoading = true;
        parent.repaint();
    }
    
    protected void doKeyCenterRemain() {
        if (dialog.isShow) {
            if (!dialog.getText().equals(gameData.tablePass[startDrawIndex + tableSelectedIndex])) {
                dialogString = "Bạn nhập sai mật khẩu";
                parent.repaint();
                dialog.show(false);
                return;
            } else {
                if (gameData.getMyMoney() > gameData.getMoneyBetOfTable()[startDrawIndex + tableSelectedIndex] * 5) {
                    Request.enterTable(startDrawIndex + tableSelectedIndex);
                    isLoading = true;
                } else {
                    dialogString = "Bạn không đủ tiền vào phòng này";
                }
                dialog.show(false);
                return;
            }
        }
        if (gameData.tablePass[startDrawIndex + tableSelectedIndex].equals("?")) {
            if (gameData.getMyMoney() > gameData.getMoneyBetOfTable()[startDrawIndex + tableSelectedIndex] * 5) {
                Request.enterTable(startDrawIndex + tableSelectedIndex);
                isLoading = true;
            } else {
                dialogString = "Bạn không đủ tiền vào phòng này";
            }
        } else {
            dialog.setString("Hãy nhập mật khẩu");
            dialog.show(true);
            parent.repaint();
            return;
        }
        parent.repaint();
    }
    
    public void inputKeyCode(int key) {
        if (dialog.isShow) {
            dialog.input(key);
            parent.repaint();
            return;
        }
        if (isShowSpeaker) {
            speakerBox.inputChar(key);
            parent.repaint();
        }
    }
    
    protected void touchPressedRemain(int x, int y) {
        isDrawSelected = false;
        isPointerDrag = false;
        pointerPressX = x;
        poiterPressY = y;
    }
    
    private void checkPointerDrag() {
        if (pointerPressX - 8 < pointerDragX && pointerDragX < pointerPressX + 8
                && poiterPressY - 8 < pointerDragY && pointerDragY < poiterPressY + 8) {
            isPointerDrag = false;
        }
    }
    
    public void doTouchReleased(int x, int y) {
        checkPointerDrag();
        if (isPointerDrag) {
            if (x - pointerPressX < 0) {
                Debug.d("move left");
                slideLeft();
                return;
            }
            if (x - pointerPressX > 0) {
                slideRight();
                Debug.d("move right");
                return;
            }
        } else {
            touchSelectTable(x, y);
        }
    }
    
    private void touchSelectTable(int touchX, int touchY) {
        Debug.d("touch Table");
        int topList = topScreen + 10 + topBarImage.getHeight();
        int leftList = leftScreen + paddingLeft;
        for (int i = startDrawIndex % NUMBER_TABLE_PER_PAGE; i < numberTablesShow; i++) {
            if (i % NUMBER_TABLE_PER_ROW == 0 && i != 0) {
                leftList = leftScreen + paddingLeft;
                topList += tableHeight + paddingTop;
            }
            
            if (Utils.isTouch(leftList - 5, topList - 5, tableWidth + 10, tableHeight + 10, touchX, touchY)) {
                tableSelectedIndex = i;
                Debug.d("table id:" + (startDrawIndex + tableSelectedIndex));
                parent.repaint();
                doKeyCenter();
                break;
            }
            leftList += tableImage.getWidth() + paddingLeft;
            
        }
        
    }
    
    private void slideLeft() {
        startDrawIndex += NUMBER_TABLE_PER_PAGE;
        tableSelectedIndex = 0;
        currentPageIndex = startDrawIndex / NUMBER_TABLE_PER_PAGE;
        if (currentPageIndex > 4) {
            currentPageIndex = 0;
        }
        if (startDrawIndex == 36) {
            numberTablesShow = 4;
        }
        if (startDrawIndex > 36 || currentPageIndex == 4 && tableSelectedIndex == 4) {
            startDrawIndex = 0;
            numberTablesShow = NUMBER_TABLE_PER_PAGE;
            currentPageIndex = 0;
        }
        parent.repaint();
    }
    
    private void slideRight() {
        startDrawIndex -= NUMBER_TABLE_PER_PAGE;
        currentPageIndex = startDrawIndex / NUMBER_TABLE_PER_PAGE;
        numberTablesShow = NUMBER_TABLE_PER_PAGE;
        if (startDrawIndex < 0) {
            startDrawIndex = 36;
            numberTablesShow = 4;
            currentPageIndex = 4;
        }
        parent.repaint();
    }
    
    public void doTouchDraged(int x, int y) {
        pointerDragX = x;
        pointerDragY = y;
        isPointerDrag = true;
    }
    
    public void processMessage(String[] part) {
        super.processMessage(part);
        Debug.d("process choose table message:" + part[0]);
        if (part[0].equals("RO")) {
            gameData.setRoArrData(part);
            return;
        }
        if (part[0].equals("MO")) {
            gameData.setMoArrData(part);
            return;
        }
        if (part[0].equals("INFO") && !isGetUserInfo) {
            gameData.setInfoData(part);
            return;
        }
        if (part[0].equals("RE")) {
            gameData.setReArrData(part);
            gameData.setTableId(startDrawIndex + tableSelectedIndex);
            isLoading = false;
            Debug.d("view id :" + gameData.getMyViewId());
            Debug.d("max player :" + gameData.getMaxPlayer());
            if (gameData.getMyViewId() < gameData.getMaxPlayer()) {
                showWaitingRoom();
            } else {
                showViewMode();
            }
            return;
        }
        if (part[0].equals("GA")) {
            isLoading = false;
            isGoBack = true;
            gameData.setGaData(part);
            showChooseRoom();
            parent.repaint();
            return;
        }
        if (part[0].equals("GM")) {
            gameData.setGameRule(Integer.parseInt(part[1]));
            return;
        }
        if (part[0].equals("CHESS")) {
            gameData.chessMapData = part;
            return;
        }
        
        if (part[0].equals("USE")) {
            processSeData(part);
            return;
        }
        if (part[0].equals("US")) {
            gameData.setMaxPlayerInTable(part);
            return;
        }
        if (part[0].equals("UUS")) {
            gameData.setMaxPlayerInTable(part);
            return;
        }
        if (part[0].equals("SE")) {
            processSeData(part);
            return;
        }
        if (part[0].equals("UPAS")) {
            gameData.setTablePass(part);
            return;
        }
        if (part[0].equals("PASS")) {
            gameData.setTablePass(part);
            return;
        }
        if (part[0].equals("NRO")) {
            dialogString = "Bạn không đủ tiền vào bàn";
            isLoading = false;
            parent.repaint();
            return;
        }
        if (part[0].equals("SPEAK")) {
            if (!part[1].equals("0")) {
                String speakString = part[1] + ": " + part[2];
                speakFlyString.setText(speakString, 3, canvasWidth, topScreen + 5);
                speakFlyString.show(15000);
                speakFlyString.setLimitHorizontal(canvasWidth);
                speakFlyString.setTextColor(PiPoDesigner.COLOR_WHITE);
            } else {
                dialogString = "Bạn cần mua item loa để nói";
            }
            parent.repaint();
            return;
        }
        if (part[0].equals("UMO")) {
            gameData.myMoney = Integer.parseInt(part[1]);
            Debug.d("money update :" + gameData.myMoney);
            return;
        }
        if (part[0].equals("SM") || part[0].equals("USM")) {
            gameData.setTableMoneyBet(part);
            parent.repaint();
            return;
        }
    }

//    private void processSmData(String[] message) {
//        for (int i = 0, l = message.length - 2; i < l; i++) {
//            moneyBetOfTables[i] = Integer.parseInt(message[i + 1]);
//        }
//        parent.repaint();
//    }
    private void processSeData(String[] message) {
        for (int i = 0, l = message.length - 1; i < l; i++) {
            numberPlayerInTable[i] = Integer.parseInt(message[i + 1]);
        }
        parent.repaint();
    }
    
    private void showViewMode() {
        switch (gamePlayType) {
            case Constants.CO_VUA:
                showChessScene();
                break;
            case Constants.TIEN_LEN:
                showTienlenScene();
                break;
            case Constants.PHOM:
                showPhomScene();
                break;
            case Constants.BA_CAY:
                showBacayScene();
                break;
        }
    }
    
    private int findTable() {
        Debug.d("number players :" + gameData.numberPlayersInTable);
        for (int i = 0; i < NUMBER_TABLES; i++) {
            if (gameData.numberPlayersInTable[i] < gameData.getMaxPlayer()) {
                Debug.d("i:" + i);
                return i;
            }
        }
        return 0;
    }
    
    protected void doSubMenu() {
        if (isShowMessage) {
            doMenuMessage();
            return;
        }
        isShowSubMenu = false;
        parent.repaint();
        switch (subMenu.getSelectedIndex()) {
            case 0:
                //thong tin ca nhan
                //  showUserInfo();
                Request.getUserInfo();
                isGetUserInfo = true;
                isLoading = true;
                parent.repaint();
                break;
            case 1:
                //choi nhanh
                int tableFound = findTable();
                Request.enterTable(tableFound);
                isLoading = true;
                parent.repaint();
                break;
            case 2:
                //hop thu
                if (gameData.userMessage == null) {
                    Request.getListMessage();
                    isLoading = true;
                } else {
                    numberMessage = gameData.numberMessage;
                    numberMessageShow = numberMessage < messageBoardHeight / ROW_HEIGHT ? numberMessage : messageBoardHeight / ROW_HEIGHT;
                    isShowMessage = true;
                    gameData.isHasNewMessage = false;
                    saveSubMenu = subMenu.getList();
                    subMenu.setList(new String[]{"Xóa", "Xóa hết", "Trả lời"});
                }
                parent.repaint();

                //hop thu
                break;
            case 3:
                //loa
                isShowSpeaker = true;
                speakerBox.setText("");
                parent.repaint();
                
                break;
        }
    }
    
    protected void reponseQuestion(int result) {
    }
    
    public void doKeyPound() {
    }
}
